package com.itheima.stargraph.job;

import com.itheima.stargraph.api.ComfyuiApi;
import com.itheima.stargraph.pojo.ComfyuiTask;
import com.itheima.stargraph.service.IUserFundService;
import com.itheima.stargraph.service.Text2ImageService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.HashMap;

/**
 * 定时添加Comfyui的工作流任务的定时任务
 *
 * @Author mr.wu
 * @Date 2025-6-12 8:53
 */
@Slf4j
@Component
public class RunWorkflowTaskJob {

    @Autowired
    private Text2ImageService text2ImageService;

    @Autowired
    private ComfyuiApi comfyuiApi;

    @Autowired
    private RedissonClient redissonClient;

    private static final String REDIS_KEY_TASK_LOCK = "star:graph:task:lock";

    @Autowired
    private IUserFundService userFundService;

    /**
     * 定时添加Comfyui的工作流任务的定时任务
     */
    @Scheduled(cron = "*/10 * * * * ?")
    public void runTask(){

        //1. 获取锁对象
        RLock lock = redissonClient.getLock(REDIS_KEY_TASK_LOCK);

        //2. 尝试加锁
        boolean result = lock.tryLock();

        //3. 加锁失败，拒绝执行
        if(!result) {
            return;
        }

        //4. 加锁成功，执行业务
        try {
            //1. 从Redis队列获取最优先执行的任务
            ComfyuiTask comfyuiTask = text2ImageService.popComfyuiTask();
            if(comfyuiTask==null) {
                return;
            }

            //2. 调用comfyui的API添加流程任务
            Call<HashMap> call = comfyuiApi.addQueueTask(comfyuiTask.getComfyuiRequestDto());

            //3. 获取comfyui添加流程任务的响应结果
            Response<HashMap> response = call.execute();
            if(!response.isSuccessful()) {
                log.error("[文生图定时任务-添加comfyui任务]任务添加失败");

                //冻结积分归还
                userFundService.refund(comfyuiTask.getUserId(), Long.valueOf(comfyuiTask.getSize()));
                return;
            }

            String promptId = String.valueOf(response.body().get("prompt_id"));
            log.info("[文生图定时任务-添加comfyui任务]任务添加完毕，任务id:{}, promptId:{}",comfyuiTask.getId(), promptId);

            //4. 缓存promptId和clientId的对应关系 （实际上指的是promptId和comfyuiTask的关系）
            text2ImageService.addStartedTask(promptId, comfyuiTask);
        }  catch (IOException e) {
            log.error("[文生图定时任务-添加comfyui任务]任务添加异常：", e);
        } finally {
            //5. 执行完业务释放锁
            lock.unlock();
        }
    }
}
